/*
 * Created on 2005-8-29
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.yeqiangwei.commons.ip;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.yeqiangwei.commons.util.StringHelper;
import com.yeqiangwei.commons.util.TypeChange;
import com.yeqiangwei.commons.util.ValidatorHelper;

/**
 * @author wang
 * @author HongGuang TODO To change the template for this generated type comment
 *         go to Window - Preferences - Java - Code Style - Code Templates
 */
public class IPUtils {

	private static final Logger logger = Logger.getLogger(IPUtils.class);

	/**
	 * 
	 */
	public IPUtils() {
		super();
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		System.out.println(IPUtils.enIpAddr("127.0.0.1"));
		System.out.println(IPUtils.enIpAddr("124.115.0.0"));

		System.out.println(IPUtils.enIpAddr("124.115.0.32"));

		System.out.println(IPUtils.deAddr("2130706432"));

		IPModel ipmodel = IPSeeker.getInstance().getIPModel("124.115.0.32");
		System.out.println(ipmodel.getCity());
		System.out.println(ipmodel.getState());
		
	}

	/**
	 * 用squid等反向代理的网站获取客户端真实IP的方法
	 * 
	 * @param request
	 * @return String
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ValidatorHelper.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ValidatorHelper.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ValidatorHelper.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip.indexOf(",") != -1) {
			ip = StringHelper.substring(ip, 0, ip.indexOf(","), ip);
		}
		return ip;
	}
	

	/**
	 * 从ip的字符串形式得到字节数组形式
	 * 
	 * @param ip
	 *            字符串形式的ip
	 * @return 字节数组形式的ip
	 */
	public static byte[] getIpByteArrayFromString(String ip) {
		byte[] ret = new byte[4];
		java.util.StringTokenizer st = new java.util.StringTokenizer(ip, ".");
		try {
			ret[0] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
			ret[1] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
			ret[2] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
			ret[3] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
		} catch (Exception e) {
			logger.error("|" + ip + "|");
			logger.error(e.toString());
		}
		return ret;
	}

	/**
	 * 对原始字符串进行编码转换，如果失败，返回原始的字符串
	 * 
	 * @param s
	 *            原始字符串
	 * @param srcEncoding
	 *            源编码方式
	 * @param destEncoding
	 *            目标编码方式
	 * @return 转换编码后的字符串，失败返回原始字符串
	 */
	public static String getString(String s, String srcEncoding,
			String destEncoding) {
		try {
			return new String(s.getBytes(srcEncoding), destEncoding);
		} catch (UnsupportedEncodingException e) {
			return s;
		}
	}

	/**
	 * 根据某种编码方式将字节数组转换成字符串
	 * 
	 * @param b
	 *            字节数组
	 * @param encoding
	 *            编码方式
	 * @return 如果encoding不支持，返回一个缺省编码的字符串
	 */
	public static String getString(byte[] b, String encoding) {
		try {
			return new String(b, encoding);
		} catch (UnsupportedEncodingException e) {
			return new String(b);
		}
	}

	/**
	 * 根据某种编码方式将字节数组转换成字符串
	 * 
	 * @param b
	 *            字节数组
	 * @param offset
	 *            要转换的起始位置
	 * @param len
	 *            要转换的长度
	 * @param encoding
	 *            编码方式
	 * @return 如果encoding不支持，返回一个缺省编码的字符串
	 */
	public static String getString(byte[] b, int offset, int len,
			String encoding) {
		try {
			return new String(b, offset, len, encoding);
		} catch (UnsupportedEncodingException e) {
			return new String(b, offset, len);
		}
	}

	/**
	 * @param ip
	 *            ip的字节数组形式
	 * @return 字符串形式的ip
	 */
	public static String getIpStringFromBytes(byte[] ip) {
		StringBuffer sb = new StringBuffer();
		sb.append(ip[0] & 0xFF);
		sb.append('.');
		sb.append(ip[1] & 0xFF);
		sb.append('.');
		sb.append(ip[2] & 0xFF);
		sb.append('.');
		sb.append(ip[3] & 0xFF);
		return sb.toString();
	}

	public static long enIpAddr(String ip) {
		return TypeChange.stringToLong(enAddr(ip));
	}

	public static String deIpAddr(String ip) {
		return deAddr(ip);
	}

	public static String deIpAddr(long ip) {
		return deAddr(String.valueOf(ip));
	}

	public static String enAddr(String ip) {
		if (ValidatorHelper.isEmpty(ip)) {
			ip = "127.0.0.1";
		}
		String esip, str1, str2, str3, str4;
		long int1=127, int2=0, int3=0, int4=0;
		try{
			int i = ip.indexOf("."); // 取小数点第一次出现的位置
			str1 = ip.substring(0, i); // 截取字符串指定长度substring 相当于vb的Mid函数。
			// 分别取出Ip各段字符串，然后转化成Integer类型
			esip = ip.substring(i + 1);
			i = esip.indexOf(".");
			str2 = esip.substring(0, i);
			esip = esip.substring(i + 1); // 截取字符串长度从i+1到字符串尾
			i = esip.indexOf(".");
			str3 = esip.substring(0, i);
			i = esip.indexOf(".");
			str4 = esip.substring(i + 1);
			int1 = Integer.parseInt(str1);
			int1 = Long.parseLong(str1);
			int2 = Long.parseLong(str2);
			int3 = Long.parseLong(str3);
			int4 = Long.parseLong(str4);
		}catch(RuntimeException e){
			logger.error("error ip = " + ip);
			logger.error(e.toString());
		}
		return String.valueOf((int1 * 256 * 256 * 256) + (int2 * 256 * 256)
				+ (int3 * 256) + int4 - 1);
	}

	public static String deAddr(String ip) {
		if (ValidatorHelper.isEmpty(ip)) {
			ip = "127.0.0.1";
		}
		long sip;
		sip = Long.parseLong(ip);
		long s1, s21, s2, s31, s3, s4;
		String temp;
		sip = sip + 1;
		s1 = sip / 256 / 256 / 256;
		s21 = s1 * 256 * 256 * 256;
		s2 = (sip - s21) / 256 / 256;
		s31 = s2 * 256 * 256 + s21;
		s3 = (sip - s31) / 256;
		s4 = sip - (s3 * 256) - s31;
		temp = String.valueOf(s1) + "." + String.valueOf(s2) + "."
				+ String.valueOf(s3) + "." + String.valueOf(s4);
		return temp;
	}

}
